<template>
  <div class="app-container details-container">
    <div class="detail-title">工单详情 <router-link to="/worklist/myWorkList"><span class="back"><i class="el-icon-back"/> 返回列表</span></router-link></div>
    <div class="status-box">
      <el-steps :active="details.istatus" align-center >
        <el-step v-for="item in iStatusStep" :key="item.key" :title="item.name"/>
      </el-steps>
    </div>

    <div v-if="details.istatus === 1" :class="{'green': workCount < 10, 'blue': workCount >= 10 && workCount < 20, 'red': workCount > 20 }" class="work-count">目前排队处理的工单数量有{{ workCount }}个</div>
    <div v-if="details.istatus > 1" class="work-count">实际处理时长 {{ timeConsuming | minuteToDay }}</div>

    <div class="work-box">
      <el-card class="box-card">
        <el-row>
          <p style="display:inline-block;line-height: 32px; vertical-align: top; padding-top:0;margin-top:0">工单描述：</p><pre style="width:92%; display:inline-block; line-height:32px; vertical-align: top; white-space: pre-wrap!important;word-wrap: break-word!important;*white-space:normal!important; margin:0; padding:0; ">{{ details.description }}</pre>
        </el-row>
        <el-row>
          <el-col :span="6">
            工单编号：{{ details.code }}
          </el-col>
          <el-col :span="6">
            提交人：{{ details.creatorName }}
          </el-col>
          <el-col :span="6">
            处理人：{{ details.opsName }}
          </el-col>
          <el-col :span="6">
            提交时间：{{ details.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            工单类型：<span v-if="details.itype > -1">{{ isTypeOptions[details.itype] }}</span><span v-else>其他</span>
          </el-col>
          <el-col v-if="(details.itype === 0 || details.itype === 1) && details.subType !== ''" :span="6">
            工单子类型：
            <span v-if="details.itype === 0">{{ details.subType == -1 ? '其他' : serverSubTypeDict[details.subType] }}</span>
            <span v-if="details.itype === 1">{{ details.subType == -1 ? '其他' : publicSubTypeDict[details.subType] }}</span>
          </el-col>
          <el-col :span="6">
            优先级：{{ priorityDict[details.ilevel] }}
          </el-col>
          <el-col :span="6">
            状态：{{ istatusOptions[details.istatus] }}
          </el-col>
        </el-row>
        <el-row v-if="details.fileVname">
          <el-col :span="12">
            下载文件：<a target="_blank" style="display:inline-block; color:#409EFF" @click="goDownloadFile(details.id)">{{ details.fileVname }}</a>
          </el-col>
        </el-row>

        <div v-if="details.workBootGroupAccess || details.workDeployAccess || details.workDeployOther || details.workOpsCommon || details.workServerApply" style="padding-top:20px">
          <el-row v-if="details.workServerApply">
            <el-col v-if="details.workServerApply.imageName" :span="8">镜像：{{ details.workServerApply.imageName }}</el-col>
            <el-col v-if="details.workServerApply.env" :span="8">应用环境：{{ details.workServerApply.env }}</el-col>
            <el-col v-if="details.workServerApply.hostName" :span="8">主机标识：{{ details.workServerApply.hostName }}</el-col>
          </el-row>
          <el-row v-if="details.workServerApply">
            <el-col v-if="details.workServerApply.dueDate" :span="12">到期时间：{{ details.workServerApply.dueDate | parseTime('{y}-{m}-{d}') }}</el-col>
          </el-row>
          <el-row v-if="details.workOpsCommon">
            <el-col :span="8">
              服务器IP：{{ details.workOpsCommon.hostIp }}
            </el-col>
          </el-row>

          <!-- 自动化平台 新应用发布 -->
          <div v-if="details.workDeployAccess">
            <el-row>
              <el-col :span="8">
                应用名称：{{ details.workDeployAccess.appName }}
              </el-col>
              <el-col :span="8">
                应用分类：{{ details.workDeployAccess.typeName }}
              </el-col>
              <el-col :span="8">
                应用类型：{{ details.workDeployAccess.systemType }}
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                应用级别：{{ details.workDeployAccess.vlevel }}
              </el-col>
              <el-col :span="16">
                git地址：{{ details.workDeployAccess.gitUrl }}
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                应用描述：{{ details.workDeployAccess.remark }}
              </el-col>
              <el-col :span="8">
                开发负责人：{{ details.workDeployAccess.ownerName }}
              </el-col>
              <el-col :span="8">
                质量负责人：{{ details.workDeployAccess.qualityName }}
              </el-col>
            </el-row>
          </div>

          <!-- 自动化平台 spring boot -->
          <div v-if="details.workBootGroupAccess">
            <el-row>
              <el-col :span="8">
                应用名称：{{ details.workBootGroupAccess.appName }}
              </el-col>
              <el-col :span="8">
                分组环境：{{ details.workBootGroupAccess.sfEnv }}
              </el-col>
              <el-col :span="8">
                spring应用名：{{ details.workBootGroupAccess.applicationName }}
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="8">
                下线后等待时间(秒)：{{ details.workBootGroupAccess.waitTime }}
              </el-col>
              <el-col :span="8">
                端口：{{ details.workBootGroupAccess.port }}
              </el-col>
              <el-col :span="8">
                eureka地址：{{ details.workBootGroupAccess.eurekaUrl }}
              </el-col>
            </el-row>
          </div>
        </div>
      </el-card>
    </div>

    <div v-if="details.istatus > 0" class="record-box">
      <div class="record-title">沟通记录</div>
      <ul v-if="recordList" class="record-list">
        <li v-for="(item, index) in recordList" :key="index">
          <p><span v-if="item.imageUrl" class="avatar"><img :src="item.imageUrl"></span><span v-if="!item.imageUrl"><i class="fa fa-user"/></span><span class="user">{{ item.userName }}</span><span class="date"> {{ item.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span></p>
          <pre style="width:98%;display:inline-block; line-height:32px;vertical-align: top; white-space: pre-wrap!important;word-wrap: break-word!important;*white-space:normal!important; margin:0; padding:0; ">{{ item.content }}</pre>
        </li>
      </ul>
      <h5 v-else>暂无沟通记录</h5>
      <el-form v-if="details.istatus > 0 && details.istatus < 3" ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="留言">
              <el-input ref="leaveMsg" :autosize="{ minRows:4, maxRows: 6}" v-model="temp.comment" :maxlength="300" type="textarea"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="end">
          <el-col :span="18" style="flaot:right">
            <el-button type="primary" @click="sendMessage">{{ $t('table.send') }}</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="opt-box">
      <el-row type="flex" justify="center">
        <el-col :span="24">
          <el-button v-if="userCode == 'ops' && details.istatus == 1 && rolesId == details.opsId" type="primary" @click="goStatement">{{ $t('table.statement') }}</el-button>
          <el-button v-if="userCode == 'ops' && details.istatus == 1 && rolesId == details.opsId" type="success" @click="goTransfer">{{ $t('table.transfer') }}</el-button>
          <el-button v-if="userCode == 'developer' && details.istatus === 0 && rolesId == details.creatorId" type="success" @click="goClose">取消工单</el-button>
          <el-button v-if="userCode == 'developer' && details.istatus === 2 && rolesId == details.creatorId" type="success" @click="goClose">关闭工单</el-button>
          <el-button v-if="userCode == 'ops' && details.istatus == 0" type="success" @click="goClaim">{{ $t('table.claimWorkOrder') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <el-dialog
      :visible.sync="claimVisible"
      title="工单转移"
      width="30%">
      <el-row>
        <el-col :span="8" class="label-item" >
          请选择工单接收人
        </el-col>
        <el-col :span="14">
          <el-select v-model="temp.opsId" class="filter-item" placeholder="请选择工单接收人">
            <el-option v-for="item in devOptions" :label="item.nickname" :key="item.id" :value="item.id"/>
          </el-select>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="claimVisible = false">取 消</el-button>
        <el-button type="primary" @click="goTransferWork">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import 'font-awesome/css/font-awesome.min.css'
import {
  fetchWorkDetails,
  fetchRecordList,
  claimWork,
  finishWork,
  transferWork,
  closeWork,
  fetchQueueCount,
  insertCommit,
  fetchOpsList,
  fetchDealTime
} from '@/api/worklist/workList'
import store from '@/store'
import { generateSign } from '@/utils/signature'
import { getToken } from '@/utils/auth'

export default {
  name: 'WorkListDetails',
  data() {
    return {
      activeStatus: 2,
      workId: this.$route.params.id || '',
      details: '',
      priorityDict: ['一般', '重要', '紧急'],
      istatusOptions: ['待受理', '待处理', '待确认', '已关闭'],
      isTypeOptions: ['服务器', '自动化发布', '域名', '修改配置', '软件安装', '其他'],
      serverSubTypeDict: ['申请', '变更配置', '调整系统参数', '其他'],
      publicSubTypeDict: ['应用新接入发布', 'Spring Cloud接入分组发布', '其他'],
      recordList: [],
      devOptions: [],
      workCount: 0,
      MIME: {
        'application/x-zip-compressed': 'zip',
        'application/javascript': 'js',
        'application/json': 'json',
        'application/xhtml+xml': 'xhtml',
        'application/vnd.ms-excel': 'xls',
        'application/vnd.ms-powerpoint': 'ppt',
        'application/pdf': 'application/pdf',
        'text/css': 'css',
        'text/plain': 'txt',
        'text/html': 'html',
        'text/xml': 'xml',
        'image/jpeg': 'jpeg',
        'image/png': 'png',
        'image/gif': 'gif',
        'image/svg+xml': 'svg',
        'audio/mpeg': 'mp3',
        'audio/mp4': 'mp4',
        'text/csv': 'csv'
      },
      temp: {
        opsId: '',
        comment: ''
      },
      userCode: store.getters.rolesCode,
      rolesId: store.getters.userId || '',
      timeConsuming: 0,
      claimVisible: false,
      downFile: {},
      iStatusStep: [
        { key: 0, name: '待受理' },
        { key: 1, name: '待处理' },
        { key: 2, name: '待确认' }
      ],
      rules: {}
    }
  },
  watch: {
    claimVisible(val) {
      if (!val) {
        this.temp.opsId = ''
      }
    }
  },
  created() {
    this.getWorkDetails()
    this.getQueueCount()
    this.getWorkRecordList()
  },
  methods: {
    updateStepStatus(status) {
      if (status === 1) {
        this.iStatusStep[0].name = '已受理'
      } else if (status === 2) {
        this.iStatusStep[0].name = '已受理'
        this.iStatusStep[1].name = '已处理'
      } else if (status === 3) {
        this.iStatusStep[0].name = '已受理'
        this.iStatusStep[1].name = '已处理'
        this.iStatusStep[2].name = '已关闭'
      }
    },
    // 处理工单耗时
    getDealTime() {
      fetchDealTime(this.workId).then(res => {
        this.timeConsuming = res.data
      })
    },
    // 工单详情
    getWorkDetails() {
      fetchWorkDetails(this.workId).then(res => {
        this.details = res.data
        if (this.details.istatus === 1) {
          this.getQueueCount()
        }
        if (this.details.istatus > 1) {
          this.getDealTime()
        }
        this.updateStepStatus(this.details.istatus)
      })
    },

    // 查询排队中工单的数量
    getQueueCount() {
      fetchQueueCount(this.workId).then(res => {
        if (res.code === 1) {
          this.workCount = res.data
        }
      })
    },
    // 获取沟通记录
    getWorkRecordList() {
      const param = {
        workSheetId: this.workId
      }
      fetchRecordList(param).then(res => {
        if (res.code === 1) {
          this.recordList = res.data.records
        }
      })
    },

    // 认领工单
    goClaim() {
      const param = {
        id: this.workId
      }
      claimWork(param).then(res => {
        if (res.code === 1) {
          this.getWorkDetails()
        }
      })
    },

    // 结单
    goStatement() {
      if (!this.temp.comment) {
        this.$alert('留言不能为空, 请给工单提交人留个言~', '提示信息', {
          confirmButtonText: '我知道了'
        }).then(() => {
          this.$nextTick(() => {
            this.$refs['leaveMsg'].focus()
          })
        })
        return false
      }

      const params = {
        id: this.workId,
        message: this.temp.comment
      }

      finishWork(params).then(res => {
        if (res.code === 1) {
          this.temp.comment = ''
          this.getWorkDetails()
          this.getQueueCount()
          this.getWorkRecordList()
          this.$router.replace('/worklist/myWorkList')
          this.$notify({
            title: '结单成功',
            message: '结单成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    // 运维人员
    fetchOps() {
      fetchOpsList().then(res => {
        this.devOptions = res.data
      })
    },

    // 转移工单
    goTransferWork() {
      if (this.rolesId === this.temp.opsId) {
        this.$alert('转移工单不能转移给自己', '错误信息', {
          confirmButtonText: '我知道了'
        })
        return false
      }
      const params = {
        id: this.workId,
        opsId: this.temp.opsId
      }
      transferWork(params).then(res => {
        this.getWorkDetails()
        this.claimVisible = false
        this.temp.opsId = ''
        this.$notify({
          title: '转移工单成功',
          message: '转移工单成功',
          type: 'success',
          duration: 2000
        })
      })
    },

    // 转移
    goTransfer() {
      this.claimVisible = true
      this.fetchOps()
    },

    // 关闭工单
    goClose() {
      const params = {
        id: this.workId
      }
      closeWork(params).then(res => {
        if (res.code === 1) {
          this.getWorkDetails()
          this.$router.replace('/worklist/myWorkList')
          this.$notify({
            title: '成功',
            message: '发送成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },

    // 提交留言
    sendMessage() {
      const params = {
        content: this.temp.comment,
        sourceId: this.workId
      }
      insertCommit(params).then(res => {
        if (res.code === 1) {
          this.temp.comment = ''
          this.getWorkRecordList()
          this.$notify({
            title: '成功',
            message: '发送成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    // 下载文件
    goDownloadFile(id) {
      window.location.href = process.env.BASE_API + '/workSheet/downloadFile/' + id + '?env=' + process.env.ENV_ROUTE +
        '&appCode=' + process.env.APP_CODE + '&sign=' + generateSign(process.env.KEY, process.env.APP_CODE) + '&token=' + getToken()
    }
    // 获取base64中的数据
    // getData(base64) {
    //   return base64.substr(base64.indexOf('base64,') + 7, base64.length)
    // },
    // // 获取文件类型
    // getContentType(base64) {
    //   return /data:([^;]*);/i.exec(base64)[1]
    // },
    // // base64转Blob
    // base64ToBlob(b64Data, contentType, sliceSize) {
    //   contentType = contentType || ''
    //   sliceSize = sliceSize || 512

    //   const byteCharacters = atob(b64Data)
    //   const byteArrays = []

    //   for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    //     const slice = byteCharacters.slice(offset, offset + sliceSize)

    //     const byteNumbers = new Array(slice.length)
    //     for (var i = 0; i < slice.length; i++) {
    //       byteNumbers[i] = slice.charCodeAt(i)
    //     }

    //     const byteArray = new Uint8Array(byteNumbers)

    //     byteArrays.push(byteArray)
    //   }

    //   return new Blob(byteArrays, { type: contentType })
    // },
    // // 获取Blob
    // getBlob(base64) {
    //   return this.base64ToBlob(this.getData(base64), this.getContentType(base64))
    // },

    // 字符串逆转
    // strturn(str) {
    //   if (str !== '') {
    //     let str1 = ''
    //     for (var i = str.length - 1; i >= 0; i--) {
    //       str1 += str.charAt(i)
    //     }
    //     return (str1)
    //   }
    // },
    // // 取文件全名名称
    // getFileName(filepath) {
    //   if (filepath !== '') {
    //     const names = filepath.split('\\')
    //     return names[names.length - 1]
    //   }
    // },
    // // 获取文件扩展名
    // getFileExt(filepath) {
    //   if (filepath !== '') {
    //     return '.' + filepath.replace(/.+\./, '')
    //   }
    // },
    // // 取文件名不带后缀
    // getFileNameNoExt(filepath) {
    //   const pos = this.strturn(this.getFileExt(filepath))
    //   const file = this.strturn(filepath)
    //   return this.getFileName(this.strturn(file.replace(pos, '')))
    // },
    // 下载文件
    // createAndDownloadFile(fileName, content) {
    //   const aLink = document.createElement('a')
    //   document.body.appendChild(aLink)
    //   const blob = this.getBlob(content)
    //   window.URL = window.URL || window.webkitURL
    //   aLink.download = fileName
    //   aLink.href = window.URL.createObjectURL(blob)
    //   setTimeout(function() {
    //     aLink.click()
    //     document.body.removeChild(aLink)
    //     window.URL.revokeObjectURL(blob)
    //     this.$notify({
    //       title: '下载成功',
    //       message: '下载成功',
    //       type: 'success',
    //       duration: 2000
    //     })
    //   }, 300)
    // },
    // 转换为文件格式
    // dataURLtoFile(dataurl, filename) {
    //   const arr = dataurl.split(',')
    //   const mime = arr[0].match(/:(.*?);/)[1]
    //   const bstr = atob(arr[1])
    //   let bstrLength = bstr.length
    //   const u8arr = new Uint8Array(bstrLength)
    //   while (bstrLength--) {
    //     u8arr[bstrLength] = bstr.charCodeAt(bstrLength)
    //   }
    //   return new File([u8arr], filename, { type: mime })
    // },
    // 下载文件
    // goDownloadFile(id) {
    //   fetchDownloadFile(id)
    //     .then(res => {
    //       if (res.hasOwnProperty('bytes') && res.length > 0) {
    //         this.createAndDownloadFile(this.details.fileVname, 'data:image/jpeg;base64,' + res)
    //       }
    //     })
    // }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.details-container {
  padding:30px;
  .el-row {
    margin-bottom: 16px;
  }
  .el-row:last-child {
    margin-bottom: 0;
  }
  .work-count {
    margin-top:20px;
    line-height:44px;
    background:#ebeef5;
    padding-left:20px;
    color: #303133;
  }
  .green {
    background:#dff8d3;
    color:#67c23a
  }
  .blue {
    background:#d3e8ff;
    color: #409eff;
  }
  .red {
    color:#F56C6C;
    background:#ffd2d2;
  }
  .detail-title {
    margin-bottom: 40px;
    line-height: 32px;
    .back {
      margin-left: 20px;
      color: #2285e1;
      cursor: pointer;
    }
  }
  .detail-title:before {
    content: "";
    margin-right: 6px;
    border-left: 2px solid #2285e1;
  }

  .work-box {
    margin-top:30px;
    border: 1px solid #e1e1e1;
  }
  .record-box {
    margin-top: 40px;

    .record-title {
      line-height: 44px;
      background: #e9f5ff;
      padding-left: 20px;
      border: 1px solid #e1e1e1;
    }
    .record-list {
      list-style: none;
      padding-bottom: 20px;
      li {
        span {
          display: inline-block;
          line-height:32px;
          vertical-align: top;
        }
        .avatar {
          width:32px;
          height:32px;
          & > img {
            width:32px;
            height:32px;
            border-radius:16px;
          }
        }
        .user {
          margin: 0 10px;
          height:32px;
        }
        .date {
          color: #9e9e9e;
        }
        padding-bottom:10px;
      }
    }

    h5 {
      text-align: center;
    }
  }

  .opt-box {
    margin-top: 20px;
    text-align: center;
  }
  .label-item{
    height:36px;
    line-height:36px;
  }
}
</style>
